import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_li_ke_jie/ui/login/login_model.dart';
import 'package:flutter_li_ke_jie/utils/navigator_util.dart';
import 'package:flutter_li_ke_jie/weight/down_text_view.dart';
import 'package:flutter_li_ke_jie/weight/submit_btn.dart';
import 'package:provider/provider.dart';

import '../../constant/app_constant.dart';
import '../../core/interface/common_interface.dart';
import '../../router/router.dart';
import '../../style/common_color.dart';
import '../../utils/img_util.dart';
import '../../utils/log.dart';
import '../../utils/reg_util.dart';

///登录页
class LoginPage extends StatefulWidget{
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with CommonInterface<LoginModel>{
  // ignore: prefer_typing_uninitialized_variables
  late TextEditingController _phoneController;
  late TextEditingController _codeController;
  late LoginModel _loginModel;//登录数据
  @override
  void initState() {
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.top,SystemUiOverlay.bottom]);
    _phoneController = TextEditingController();
    _codeController = TextEditingController();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    //简化model
   _loginModel = model(context);
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          color: Colors.white
        ),
        child:NotificationListener<OverscrollIndicatorNotification>(
          onNotification: (OverscrollIndicatorNotification? overscroll) {
            overscroll!.disallowGlow();
            return true;
          },
          child: ListView(
            padding: const EdgeInsets.only(left: 20,right: 20),
            children: [
              const SizedBox(height: 80,),
              Image.asset(ImageUtil.loadLocalImg("logo.png"),height: 80,width: 80,),
              const SizedBox(height: 60,),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: const [
                  Text("登录",style: TextStyle(color: color_333,fontSize: 26,fontWeight: FontWeight.bold),),
                  Text(appName,style: TextStyle(color: themeColor,fontSize: 30,fontWeight: FontWeight.bold),),
                ],
              ),
              const SizedBox(height: 10,),
              const Text("初次登录既为自动注册账号",style: TextStyle(color: color_333,fontSize: 20,fontWeight: FontWeight.bold),),
              const SizedBox(height: 30,),
              _phoneWidget(),//手机号
              const SizedBox(height: 20,),
              _codeWidget(),
              const SizedBox(height: 60,),
              _loginBtn(),
              const SizedBox(height: 20,),
              _bottomAgreement()
            ],
          ),
        ),
      ),
    );
  }

  //手机号组件
  Widget _phoneWidget(){
    return Container(
      // height: 50,
      alignment: Alignment.center,
      child: TextField(
        controller: _phoneController,
        maxLength: 11,
        maxLines: 1,
        keyboardType: TextInputType.phone,
        cursorColor: themeColor,
        style: TextStyle(fontSize: 18,color: color_333),
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.all(0),
          counterText: "",
          prefixIcon: Icon(Icons.phone_android),
          hintText: "请输入手机号码",
          hintStyle:  TextStyle(fontSize: 16),
          labelText: "手机号",
          labelStyle:  TextStyle(fontSize: 16),
          errorText:_loginModel.validatePhone ? '手机号格式错误' : null,
          border:const OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(50)),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: const BorderRadius.all(Radius.circular(50)),
            borderSide: BorderSide(
              color: Colors.blue.withOpacity(0.3),  // 边框颜色
            ),
          ),
          focusedBorder: const OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(50)),
            borderSide: BorderSide(
              color: themeColor,  // 边框颜色
            ),
          ),
        ),
        onChanged: (text){
          //校验手机号
          // Provider.of<LoginModel>(context).checkPhone(text);
          _loginModel.checkPhone(text,_codeController.text);
        },
      ),
    );
  }

  //验证码组件
  Widget _codeWidget(){
    return Container(
      alignment: Alignment.center,
      child: Row(
        children: [
          Expanded(
            child:  TextField(
              controller: _codeController,
              maxLines: 1,
              maxLength: 6,
              keyboardType: TextInputType.text,
              cursorColor: themeColor,
              style: const TextStyle(fontSize: 18,color: color_333),
              decoration: InputDecoration(
                 contentPadding: const EdgeInsets.all(0),
                  counterText: "",
                  prefixIcon: const Icon(Icons.message),
                  hintText: "请输入验证码",
                  hintStyle:  const TextStyle(fontSize: 16),
                  labelText: "验证码",
                  labelStyle: const TextStyle(fontSize: 16),
                  errorText:_loginModel.validateCode ? '请输入验证码' : null,
                border:const OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: const BorderRadius.all(Radius.circular(50)),
                  borderSide: BorderSide(
                    color: Colors.blue.withOpacity(0.3),  // 边框颜色
                  ),
                ),
                focusedBorder: const OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                  borderSide: BorderSide(
                    color: themeColor,  // 边框颜色
                  ),
                ),
              ),
              onChanged: (text){
                //校验登录
                _loginModel.checkCode(_phoneController.text,text);
              },
            ), flex: 1,),
          const SizedBox(width: 10,),
          DownTextView("获取验证码",time: 60,startCallback: (){
            //发送验证码
            _loginModel.sendCode(_phoneController.text);
            return !_loginModel.validatePhone;
          }),
        ],
      ),
    );
  }

  //登录按钮
  Widget _loginBtn(){
    return SubmitButton("登录",clickCallback: (){
      if(_loginModel.hasLogin){
        //才可以登录
        _loginModel.login(_phoneController.text, _codeController.text);
      }
    },isEnabled: _loginModel.hasLogin);
  }

  /// 用户协议中“低调”文本的样式。
  final TextStyle _lowProfileStyle = const TextStyle(
    fontSize: 16,
    color: Colors.grey,
  );

  /// 用户协议中“高调”文本的样式。
  final TextStyle _highProfileStyle = const TextStyle(
    fontSize: 16,
    color:themeColor,
  );

  //协议
  Widget _bottomAgreement(){
    return Container(
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left:40,right: 40),
        child: RichText(
          textAlign: TextAlign.center,
          softWrap: true,
          text: TextSpan(
            // 文本（`text`）属性，跨度中包含的文本。
            text: '登录即同意',
            // 样式（`style`）属性，应用于文本和子组件的样式。
            style: _lowProfileStyle,
            children: [
              TextSpan(
                // 识别（`recognizer`）属性，一个手势识别器，它将接收触及此文本范围的事件。
                // 手势（`gestures`）库的点击手势识别器（`TapGestureRecognizer`）类，识别点击手势。
                  text: '“服务条款”',
                  style: _highProfileStyle,
                  recognizer: TapGestureRecognizer()..onTap = () {
                    print("点击了服务条款");
                  }
              ),
              TextSpan(
                text: '和',
                style: _lowProfileStyle,
              ),
              TextSpan(
                  text: '“隐私政策”',
                  style: _highProfileStyle,
                  recognizer: TapGestureRecognizer()..onTap = () {
                    print("点击了隐私政策");
                  }
              ),
            ],
          ),
        ),
      ),
    );
  }
}
